package com.leetcode.offer.chapter4;

import com.leetcode.basic.Node;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Dennis Li
 * @date 2020/7/14 10:33
 */
/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/
public class CopyRandomList_35 {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Map<Integer, Node> map = new HashMap<>();
        Map<Integer, Integer> aux = new HashMap<>();
        Node p = head;
        while (p != null) {
            map.put(p.val, new Node(p.val));
            if (p.random == null) aux.put(p.val, null);
            else aux.put(p.val, p.random.val);
            p = p.next;
        }
        p = head;
        while (p != null) {
            if (p.next != null) map.get(p.val).next = map.get(p.next.val);
            map.get(p.val).random = aux.get(p.val) == null ? null : map.get(aux.get(p.val));
            p = p.next;
        }
        return map.get(head.val);
    }

    public Node copyRandomList2(Node head) {
        // 注意这里会出现值重复的情况，要用节点的对象来作为key-value
        // 正确解法之一 -- 散列表通过原节点 - 新节点建立!
        Map<Node, Node> map = new HashMap<>();
        Node p = head;
        while (p != null) {
            map.put(p, new Node(p.val));
            p = p.next;
        }
        p = head;
        while (p != null) {
            map.get(p).next = map.get(p.next);
            map.get(p).random = map.get(p.random);
            p = p.next;
        }
        return map.get(head);
    }

}
